package com.bd.scm.module.uploadFile.service.impl;

import com.bd.scm.domain.models.enclosure.BdEnclosure;
import com.bd.scm.module.enums.UploadTypeEnum;
import com.bd.scm.module.uploadFile.service.UploadFileService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Mason
 * @version 1.0
 * @since 2020/1/4 13:35
 */
@Service
public class UploadFileServiceImpl implements UploadFileService {
    //临时目录
    @Value("${bd.upload.tempDir}")
    private volatile String tempDir;
    //有效附件目录
    @Value("${bd.upload.effectiveDir}")
    private volatile String effectiveDir;


    /**
     * 保存文件到临时目录.
     *
     * @param file
     * @return
     */
    @Override
    public String saveTempFile(MultipartFile file) {
        SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
        //保存的文件名
        String newFileName = sf_.format(new Date()) + file.getOriginalFilename();
        if (!(new File(tempDir).isDirectory())) {
            new File(tempDir).mkdir();
        }
        File dest = new File(tempDir + newFileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {

        }
        return newFileName;
    }

    /**
     * 保存到有效附件目录.
     *
     * @param fileNames      文件名集合
     * @param uploadTypeEnum 上传的业务类型
     * @param orderId        单号
     * @return
     */
    @Override
    public List<BdEnclosure> saveEffectiveFile(List<String> fileNames, UploadTypeEnum uploadTypeEnum, Integer orderId) {
        //确保文件夹存在
        if (!(new File(effectiveDir).isDirectory())) {
            new File(effectiveDir).mkdir();
        }
        List<BdEnclosure> list = new ArrayList<>();
        File tempFile = null;
        File effectiveFile = null;
        String effectivePath = effectiveDir + uploadTypeEnum.getName();
        //确保文件夹存在
        if (!(new File(effectivePath).isDirectory())) {
            new File(effectivePath).mkdir();
        }
        Integer orderType = uploadTypeEnum.getCode();

        for (String fileName : fileNames) {
            tempFile = new File(tempDir + fileName);
//          copyFileUsingFileStreams(tempFile, effectiveFile);
//          deleteFiles(tempFile);
            removeFile(tempFile, effectivePath);
            BdEnclosure bdEnclosure = new BdEnclosure();
            bdEnclosure.setOrderId(orderId);
            bdEnclosure.setEnclosureAddr(effectivePath + fileName);
            bdEnclosure.setOrderType(orderType);
            bdEnclosure.setOriginalName(fileName.substring(14));
            list.add(bdEnclosure);
        }
        return list;
    }

    /**
     * 文件复制.
     *
     * @param source
     * @param dest
     * @throws IOException
     */
    private static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }

    /**
     * 删除文件、文件夹.
     *
     * @param file
     * @return
     */
    public static boolean deleteFiles(File file) {

        if (!file.exists()) {
            return false;
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                deleteFiles(f);
            }
        }
        return file.delete();
    }

    /*
     * 删除指定文件.
     *
     * @param file
     * @return
     */
    public static void deleteFilesByName(List<String> list, String filePath) {
        for (String fileName : list) {
            File file = new File(filePath + fileName);
            deleteFiles(file);
        }
    }

    /*
     * 移动文件.
     *
     * @param file
     * @return
     */
    public static void removeFile(File file, String targetPath) {
        file.renameTo(new File(targetPath + file.getName()));
    }
}
